package cli

import (
	"fmt"

	cli "github.com/urfave/cli/v2"
	"golang.org/x/xerrors"
)

var SlaveCmd = &cli.Command{
	Name:  "slave",
	Usage: "操作端口映射",
	Subcommands: []*cli.Command{
		startSlaveCmd,
		stopSlaveCmd,
	},
}

var startSlaveCmd = &cli.Command{
	Name:  "start",
	Usage: "启动一个端口映射 localhost:port1  port2",
	Flags: []cli.Flag{
		&cli.StringFlag{
			Name:  "from",
			Usage: "映射源地址 例如: 127.0.0.1:3389",
		},
		&cli.StringFlag{
			Name:  "to",
			Usage: "映射端口 例如: 5000",
		},
	},
	Action: func(cctx *cli.Context) error {
		from := cctx.String("from")
		to := cctx.String("to")
		if from == "" || to == "" {
			return xerrors.New("parameter error")
		}
		api, closer, err := GetClientAPI()
		if err != nil {
			return err
		}
		defer closer()

		err = api.StartSlave(from, to)
		fmt.Printf("StartSlave : %s -> %s %v\n", from, to, err)

		return err
	},
}

var stopSlaveCmd = &cli.Command{
	Name:  "stop",
	Usage: "停止一个端口映射 localhost:port1",
	Flags: []cli.Flag{
		&cli.StringFlag{
			Name:  "from",
			Usage: "映射源地址 例如: 127.0.0.1:3389",
		},
	},
	Action: func(cctx *cli.Context) error {
		from := cctx.String("from")
		if from == "" {
			return xerrors.New("parameter error")
		}
		api, closer, err := GetClientAPI()
		if err != nil {
			return err
		}
		defer closer()

		err = api.StopSlave(from)
		fmt.Printf("StopSlave : %s %v\n", from, err)

		return err
	},
}
